import {useRoute} from "vue-router";
export interface BasicTabcheckProps{
    // 已选数据
    checkList:string[],
    // 更多字段选项列表
    checkListOptions:any[],
    // 更多字段选项列表更新方法
    checkListOptionsSetFn:Function,
    // 额外标识
    key?:string
}


export function useTabcheck(options:BasicTabcheckProps){
    const route = useRoute();
    const ItemKEY = route.path+(options.key||'')
    init()
    // 更多字段选项字段映射
    const checkListOptionsFn = (prop: string)=> {
        let result = options.checkListOptions.find((n) => n.value == prop);
        if (result) {
            return result.label;
        }
    }
    const checkListShow = (key:any)=>{
        return options.checkList.includes(key)
    }
    const setItemCheckList = (val:any)=>{
        let tableTerm = getALLCheckList()
        let index = tableTerm.findIndex((n:any)=>n.key == ItemKEY)
        if(index !== -1){
            tableTerm[index].list = val
            window.localStorage.setItem('tableTerm', JSON.stringify(tableTerm));
        }else{
            tableTerm.push({
                key:ItemKEY,
                list:val
            })
            window.localStorage.setItem('tableTerm', JSON.stringify(tableTerm));
        }
    }
    const getItemCheckList = ()=>{
        let tableTerm = getALLCheckList()
        let item = tableTerm.find((n:any)=>n.key == ItemKEY)
        if(item){
            return item
        }else{
            let list = <any>[]
            for (const item of options.checkListOptions) {
                if(item.check){
                    list.push(item.value)
                }
            }
            tableTerm.push({
                key:ItemKEY,
                list:list
            })
            window.localStorage.setItem('tableTerm', JSON.stringify(tableTerm));
            return getItemCheckList()
        }
    }
    const getALLCheckList= ()=>{
        let tableTerm = window.localStorage.getItem('tableTerm')
        if(tableTerm){
            return  JSON.parse(tableTerm)
        }else{
            console.log(window.localStorage.getItem('tableTerm'))
            return JSON.parse(window.localStorage.getItem('tableTerm') || '[]')
        }
    }
    // 初始化
    function init(){
        if(options.checkListOptionsSetFn){
            options.checkListOptions = options.checkListOptionsSetFn()
        }
    }
    onMounted(() => {
        let item = getItemCheckList();
        options.checkList = item.list;
    });
    return {
        checkListOptionsFn,
        checkListShow,
        setItemCheckList,
        getItemCheckList,
        init
    }
}